package com.teach.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.teach.commons.FileUtil;

@WebServlet("/upload.s")
@MultipartConfig(maxFileSize = 100*1024*1024,maxRequestSize = Long.MAX_VALUE)
public class UploadServlet extends HttpServlet {
	
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String aa = request.getParameter("aa");//无意义 
		String bb = request.getParameter("bb");
//		System.out.format("aa=%s\nbb=%s\n",aa,bb);
//		System.out.print(String.format("aa=%s\nbb=%s\n",aa,bb));
		log.debug("aa={},bb={}",aa,bb);
		
		//获取一个表单元素name=aa的文件
		Part aaPart = request.getPart("aa");
		log.debug("aaPart={}",aaPart);
		//获取所有文件的集合
		Collection<Part> coll = request.getParts();
		
		//Part对象的一些常用属性
		log.debug("getName：{}",aaPart.getName());
		log.debug("getSubmittedFileName：{}",aaPart.getSubmittedFileName());
		log.debug("getContentType：{}",aaPart.getContentType());
		log.debug("getSize：{}",aaPart.getSize());
		log.debug("getInputStream：{}",aaPart.getInputStream());
		
		String root = getServletContext().getRealPath("/");
		log.debug("root:{}",root);
		String uri = "upload/"+new SimpleDateFormat("yyyy/MM/dd/").format(new Date())+UUID.randomUUID().toString()+"/";
		log.debug("uri:{}",uri);
		
		new File(root,uri).mkdirs();
		
		uri += aaPart.getSubmittedFileName();
		FileUtil.copy(aaPart.getInputStream(), new FileOutputStream(new File(root,uri)));
		
		
	}
}
